package com.gexiaobao.pigeon.ui.breeding_pigeon

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.text.InputFilter
import android.view.View
import android.widget.LinearLayout
import android.widget.ListPopupWindow
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.core.widget.addTextChangedListener
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseActivity
import com.gexiaobao.pigeon.app.ext.showMessage
import com.gexiaobao.pigeon.app.model.bean.BloodLineDictionaryResponse
import com.gexiaobao.pigeon.app.model.bean.EditBloodInfoBean
import com.gexiaobao.pigeon.app.model.bean.ListCountryBean
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.databinding.ActivityAddElderBinding
import com.gexiaobao.pigeon.ui.adapter.AddBloodPigeonPopAdapter
import com.gexiaobao.pigeon.ui.dialog.RxInputCustomDialog
import com.gexiaobao.pigeon.viewmodel.BreedingPigeonViewModel
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.finish
import me.hgj.jetpackmvvm.util.startActivityForResult
import java.util.Calendar


/**
 * @Author      : hxw
 * @Date        : 2024/9/14 8:35
 * @Describe    : 添加祖辈
 */
class ActivityAddElder : BaseActivity<BreedingPigeonViewModel, ActivityAddElderBinding>() {

    private var pigeonSex = ""
    private var mTitle = ""
    private var mLevelInfo = ""
    private var mLevel = 0

    //选取年国家/地区
    private var adapterCountry: AddBloodPigeonPopAdapter? = null
    private val mCountryList: ArrayList<String> = arrayListOf()
    private val popWindowCountry: ListPopupWindow by lazy { ListPopupWindow(this) }
    private var countryList: ArrayList<ListCountryBean> = arrayListOf()
    private var country = ""
    private var countryEn = ""
    private var mPositionCountry = 2

    //选取年份
    private var adapterYear: AddBloodPigeonPopAdapter? = null
    private var mYearList: MutableList<String> = arrayListOf()
    private val popWindowYear: ListPopupWindow by lazy { ListPopupWindow(this) }
    private var mYearPosition = 1

    @SuppressLint("SetTextI18n")
    override fun initView(savedInstanceState: Bundle?) {
        StatusBarUtil.setTranslucentForImageView(this, 0, null)
        pigeonSex = getString(R.string.hint_unknown)
        mTitle = intent.getStringExtra("title").toString().trim()
        mDatabind.includeBar.tvTitle.text = getString(R.string.addition) + mTitle
        refreshLevelInfo(mTitle)

        val type = intent.getIntExtra("type", 0)
        if (type == 2) {//编辑
            if (mTitle.contains("主鸽")) {
                mDatabind.tvUnKnow.isVisible = true
                mDatabind.llFemale.isVisible = true
                mDatabind.llMale.isVisible = true
            } else if (mTitle.contains("父")) {
                mDatabind.tvUnKnow.isVisible = false
                mDatabind.llFemale.isVisible = false
                mDatabind.llMale.isVisible = true
                pigeonSex = getString(R.string.hint_male)
            } else {
                mDatabind.tvUnKnow.isVisible = false
                mDatabind.llFemale.isVisible = true
                mDatabind.llMale.isVisible = false
                pigeonSex = getString(R.string.hint_female)
            }
            val data = intent.getParcelableExtra<EditBloodInfoBean>("data")
            if (data != null) {
                val ringId = data.ringId
                if (ringId.isNotEmpty() && ringId.contains("-")) {
                    val result = ringId.split("-")
                    if (result.size == 3) {
                        mDatabind.tvYear.text = result[0]
                        mDatabind.etAreaCode.setText(result[1])
                        mDatabind.etRingId.setText(result[2])
                    }
                }
                when (data.sex) {
                    "雌" -> mDatabind.llFemale.isSelected = true
                    "雄" -> mDatabind.llMale.isSelected = true
                    else -> mDatabind.tvUnKnow.isSelected = true
                }
                country = data.country
                countryEn = data.countryEn
                pigeonSex = data.sex
            }
            mDatabind.data = data
        } else {
            if (mTitle.contains("母")) {
                pigeonSex = getString(R.string.hint_female)
                mDatabind.tvUnKnow.isVisible = false
                mDatabind.llFemale.isVisible = true
                mDatabind.llMale.isVisible = false
                mDatabind.llFemale.isSelected = true
            } else if (mTitle.contains("父")) {
                pigeonSex = getString(R.string.hint_male)
                mDatabind.tvUnKnow.isVisible = false
                mDatabind.llFemale.isVisible = false
                mDatabind.llMale.isVisible = true
                mDatabind.llMale.isSelected = true
            } else {
                pigeonSex = getString(R.string.hint_unknown)
                mDatabind.tvUnKnow.isVisible = true
                mDatabind.llFemale.isVisible = true
                mDatabind.llMale.isVisible = true
                mDatabind.tvUnKnow.isSelected = true
                mDatabind.llFemale.isSelected = false
                mDatabind.llMale.isSelected = false
            }
        }
        initListener()

        /** 创建一个 InputFilter */
        val filter = InputFilter { source, _, _, _, _, _ ->
            val allowedCharacters = "^[a-zA-Z0-9]*$"
            if (source != null && !source.matches(allowedCharacters.toRegex())) {
                ""
                /** 不允许输入不匹配的字符 */
                /** 不允许输入不匹配的字符 */
            } else {
                null
                /** 允许输入的字符 */
                /** 允许输入的字符 */
            }
        }

        /** 将 InputFilter 设置到 EditText */
        mDatabind.etAreaCode.filters = arrayOf(filter)
        mDatabind.etRingId.filters = arrayOf(filter)

    }

    private fun refreshLevelInfo(mTitle: String) {
        when (mTitle) {
            "主鸽" -> {
                mLevel = 1
                mLevelInfo = "1"
            }

            "父亲" -> {
                mLevel = 2
                mLevelInfo = "1-1"
            }

            "母亲" -> {
                mLevel = 2
                mLevelInfo = "1-2"
            }

            "祖父" -> {
                mLevel = 3
                mLevelInfo = "1-1-1"
            }

            "祖母" -> {
                mLevel = 3
                mLevelInfo = "1-1-2"
            }

            "外祖父" -> {
                mLevel = 3
                mLevelInfo = "1-2-1"
            }

            "外祖母" -> {
                mLevel = 3
                mLevelInfo = "1-2-2"
            }

            "曾祖父" -> {
                mLevel = 4
                mLevelInfo = "1-1-1-1"
            }

            "曾祖母" -> {
                mLevel = 4
                mLevelInfo = "1-1-1-2"
            }

            "曾外祖父" -> {
                mLevel = 4
                mLevelInfo = "1-1-2-1"
            }

            "曾外祖母" -> {
                mLevel = 4
                mLevelInfo = "1-1-2-2"
            }

            "外曾祖父" -> {
                mLevel = 4
                mLevelInfo = "1-2-1-1"
            }

            "外曾祖母" -> {
                mLevel = 4
                mLevelInfo = "1-2-1-2"
            }

            "外曾外祖父" -> {
                mLevel = 4
                mLevelInfo = "1-2-2-1"
            }

            "外曾外祖母" -> {
                mLevel = 4
                mLevelInfo = "1-2-2-2"
            }

            "高祖父" -> {
                mLevel = 5
                mLevelInfo = "1-1-1-1-1"
            }

            "高祖母" -> {
                mLevel = 5
                mLevelInfo = "1-1-1-1-2"
            }

            "高外祖父" -> {
                mLevel = 5
                mLevelInfo = "1-1-1-2-1"
            }

            "高外祖母" -> {
                mLevel = 5
                mLevelInfo = "1-1-1-2-2"
            }

            "曾外曾祖父" -> {
                mLevel = 5
                mLevelInfo = "1-1-2-1-1"
            }

            "曾外曾祖母" -> {
                mLevel = 5
                mLevelInfo = "1-1-2-1-2"
            }

            "曾外曾外祖父" -> {
                mLevel = 5
                mLevelInfo = "1-1-2-2-1"
            }

            "曾外曾外祖母" -> {
                mLevel = 5
                mLevelInfo = "1-1-2-2-2"
            }

            "外高祖父" -> {
                mLevel = 5
                mLevelInfo = "1-2-1-1-1"
            }

            "外高祖母" -> {
                mLevel = 5
                mLevelInfo = "1-2-1-1-2"
            }

            "外高外祖父" -> {
                mLevel = 5
                mLevelInfo = "1-2-1-2-1"
            }

            "外高外祖母" -> {
                mLevel = 5
                mLevelInfo = "1-2-1-2-2"
            }

            "外曾外曾祖父" -> {
                mLevel = 5
                mLevelInfo = "1-2-2-1-1"
            }

            "外曾外曾祖母" -> {
                mLevel = 5
                mLevelInfo = "1-2-2-1-2"
            }

            "外曾外曾外祖父" -> {
                mLevel = 5
                mLevelInfo = "1-2-2-2-1"
            }

            "外曾外曾外祖母" -> {
                mLevel = 5
                mLevelInfo = "1-2-2-2-2"
            }
        }
    }

    @SuppressLint("SetTextI18n")
    private fun initListener() {
        mDatabind.llMale.setOnClickListener {
            selectedPigeonSex("male")
        }
        mDatabind.llFemale.setOnClickListener {
            selectedPigeonSex("female")
        }
        mDatabind.tvUnKnow.setOnClickListener {
            selectedPigeonSex("unKnow")
        }

        mDatabind.etRingId.addTextChangedListener {
            if (it != null) {
                mDatabind.ivCleanRingId.isVisible = it.isNotEmpty()
            }
        }

        mDatabind.etNickName.addTextChangedListener {
            if (it != null) {
                mDatabind.ivCleanNickName.isVisible = it.isNotEmpty()
            }
        }

        mDatabind.etAddElderFeatherColor.addTextChangedListener {
            if (it != null) {
                mDatabind.ivCleanFeatherColor.isVisible = it.isNotEmpty()
            }
        }

        mDatabind.etAddElderEye.addTextChangedListener {
            if (it != null) {
                mDatabind.ivCleanEye.isVisible = it.isNotEmpty()
            }
        }


        mDatabind.etRingId.onFocusChangeListener = View.OnFocusChangeListener { _, hasFocus ->
            val bg: Int = if (hasFocus) {
                R.drawable.border6_red_ll
            } else {
                R.drawable.border6_gray_ll
            }
            mDatabind.llRingId.background = ContextCompat.getDrawable(this, bg)
        }

        mDatabind.etNickName.onFocusChangeListener = View.OnFocusChangeListener { _, hasFocus ->
            val bg: Int = if (hasFocus) {
                R.drawable.border6_red_ll
            } else {
                R.drawable.border6_gray_ll
            }
            mDatabind.llFeatherNickName.background = ContextCompat.getDrawable(this, bg)
        }

        mDatabind.etAddElderFeatherColor.onFocusChangeListener = View.OnFocusChangeListener { _, hasFocus ->
            val bg: Int = if (hasFocus) {
                R.drawable.border6_red_ll
            } else {
                R.drawable.border6_gray_ll
            }
            mDatabind.llFeatherColor.background = ContextCompat.getDrawable(this, bg)
        }

        mDatabind.etAddElderEye.onFocusChangeListener = View.OnFocusChangeListener { _, hasFocus ->
            val bg: Int = if (hasFocus) {
                R.drawable.border6_red_ll
            } else {
                R.drawable.border6_gray_ll
            }
            mDatabind.llAddElderEye.background = ContextCompat.getDrawable(this, bg)
        }

        popWindowCountry.setOnItemClickListener { _, _, position, _ ->
            mPositionCountry = position
            if (position != 0 && position != 1) {
                adapterCountry?.setCheckItem(position)
                countryEn = countryList[position - 2].data
                country = countryList[position - 2].name
                mDatabind.tvCountryNameEn.text = "$countryEn $country"
            } else {
                if (mCountryList[position] == "未知") {
                    mDatabind.tvCountryNameEn.text = getString(R.string.hint_unknown)
                } else {
                    showInputCustomDialog()
                }
            }
            popWindowCountry.dismiss()
        }

        popWindowYear.setOnItemClickListener { _, _, position, _ ->
            mYearPosition = position
            adapterYear?.setCheckItem(position)
            mDatabind.tvYear.text = mYearList[position]
            popWindowYear.dismiss()
        }
    }

    override fun createObserver() {
        super.createObserver()
        /** 获取国家/地区列表 */
        mViewModel.getBloodLineDictionaryResult.observe(this) {
            setCountryList(it)
        }
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(
            mDatabind.includeBar.ivBack,
            mDatabind.ivCleanRingId,
            mDatabind.ivCleanNickName,
            mDatabind.ivCleanFeatherColor,
            mDatabind.ivCleanEye,
            mDatabind.btnSave,
            mDatabind.llCountryNameEn,
            mDatabind.llYear,
            mDatabind.tvAddBloodDescribe
        ) {
            when (it) {
                mDatabind.tvAddBloodDescribe -> {
                    val describe = mDatabind.tvAddBloodDescribe.text.toString().trim()
                    startActivityForResult<ActivityEditDescribeInfo>(
                        "title" to getString(R.string.Breeding_pigeon_data_description),
                        "describe" to describe,
                        "type" to 1
                    ) { data ->
                        if (data != null) {
                            mDatabind.tvAddBloodDescribe.text = data.getStringExtra("describe")
                        }
                    }
                }

                mDatabind.llYear -> setYearPopList()
                mDatabind.llCountryNameEn -> mViewModel.getBloodLineDictionary()
                mDatabind.btnSave -> saveBloodPigeonInfo()
                mDatabind.ivCleanEye -> mDatabind.etAddElderEye.setText("")
                mDatabind.ivCleanFeatherColor -> mDatabind.etAddElderFeatherColor.setText("")
                mDatabind.ivCleanNickName -> mDatabind.etNickName.setText("")
                mDatabind.ivCleanRingId -> mDatabind.etRingId.setText("")
                mDatabind.includeBar.ivBack -> finish()
            }
        }
    }

    private fun saveBloodPigeonInfo() {
        val countryName = mDatabind.tvCountryNameEn.text.toString().trim()
        val year = mDatabind.tvYear.text.toString().trim()
        val areaCode = mDatabind.etAreaCode.text.toString().trim().ifEmpty { "00" }
        val ringId = mDatabind.etRingId.text.toString().trim()
        val nickName = mDatabind.etNickName.text.toString().trim()
        val mFeatherColor = mDatabind.etAddElderFeatherColor.text.toString().trim()
        val mEye = mDatabind.etAddElderEye.text.toString().trim()
        val mGradesDesc = mDatabind.tvAddBloodDescribe.text.toString().trim()
        when {
            country.isEmpty() && countryEn.isEmpty() && countryName.isEmpty() -> showMessage(getString(R.string.Please_select_a_country))
            ringId.isEmpty() -> showMessage(getString(R.string.Please_fill_in_the_foot_ring_number))
            else -> {
                val mRingId = "$year-$areaCode-$ringId"
                val bean = EditBloodInfoBean(
                    1, country, countryEn, mEye, mFeatherColor, mGradesDesc, mLevel, mLevelInfo,
                    nickName, mRingId, pigeonSex, mTitle
                )
                val intent = Intent()
                intent.putExtra("data", bean)
                intent.putExtra("edit", 1)
                finish(intent)
            }
        }
    }

    private fun setYearPopList() {
        mYearList.clear()
        val mList = getYearsFrom1980ToNextYear()
        mYearList = mList.reversed().toMutableList()
        adapterYear = AddBloodPigeonPopAdapter(this, mYearList)
        popWindowYear.setAdapter(adapterYear)
        popWindowYear.anchorView = mDatabind.llYear//设置ListPopupWindow的锚点，关联mButton位置
        popWindowYear.width = LinearLayout.LayoutParams.WRAP_CONTENT
        popWindowYear.height = LinearLayout.LayoutParams.WRAP_CONTENT
        popWindowYear.isModal = true
        popWindowYear.show()
        adapterYear!!.setCheckItem(mYearPosition)
    }

    private fun setCountryList(it: BloodLineDictionaryResponse?) {
        mCountryList.clear()
        if (it != null && it.list.isNotEmpty()) {
            countryList.clear()
            countryList.addAll(it.list)
            it.list.forEach {
                mCountryList.add(it.data + " " + it.name)
            }
            mCountryList.add(0, getString(R.string.hint_unknown))
            mCountryList.add(1, getString(R.string.custom))
        }
        /** 初始化ListPopupWindow，适配 */
        adapterCountry = AddBloodPigeonPopAdapter(this, mCountryList)
        popWindowCountry.setAdapter(adapterCountry)
        popWindowCountry.anchorView = mDatabind.llCountryNameEn//设置ListPopupWindow的锚点，关联mButton位置
        popWindowCountry.width = LinearLayout.LayoutParams.WRAP_CONTENT
        popWindowCountry.height = LinearLayout.LayoutParams.WRAP_CONTENT
        popWindowCountry.isModal = true
        popWindowCountry.show()
        adapterCountry!!.setCheckItem(mPositionCountry)
    }

    private fun getYearsFrom1980ToNextYear(): MutableList<String> {
        val currentYear = Calendar.getInstance().get(Calendar.YEAR)
        return (1980..currentYear + 1).map { it.toString() }.toMutableList()
    }

    private fun selectedPigeonSex(type: String) {
        val isSelect = true
        when (type) {
            "male" -> {
                pigeonSex = getString(R.string.hint_male)
                mDatabind.llMale.isSelected = isSelect
                mDatabind.tvUnKnow.isSelected = !isSelect
                mDatabind.llFemale.isSelected = !isSelect
            }

            "female" -> {
                pigeonSex = getString(R.string.hint_female)
                mDatabind.llMale.isSelected = !isSelect
                mDatabind.tvUnKnow.isSelected = !isSelect
                mDatabind.llFemale.isSelected = isSelect
            }

            "unKnow" -> {
                pigeonSex = getString(R.string.hint_unknown)
                mDatabind.llMale.isSelected = !isSelect
                mDatabind.tvUnKnow.isSelected = isSelect
                mDatabind.llFemale.isSelected = !isSelect
            }
        }
    }

    private fun showInputCustomDialog() {
        val dialog = RxInputCustomDialog(this)
        dialog.setHintText(getString(R.string.max_number_of_12_letters))
        dialog.setEnglishFilter()
        dialog.setTransInformation()
        dialog.setTitle("请输入" + getString(R.string.country_area))
        dialog.setSureListener {
            val customCountry = dialog.getContent()
            if (customCountry.isEmpty()) {
                RxToast.warning("请输入" + getString(R.string.country_area))
                return@setSureListener
            }
            mDatabind.tvCountryNameEn.text = customCountry
            dialog.dismiss()
        }
        dialog.setFullScreenWidth()
        dialog.show()
    }

}